package com.zhangsun.newMvvm.viewModel;

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;

import com.zhangsun.newMvvm.base.bean.PageBean;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.base.enums.PagingLoadTypeEnum;
import com.zhangsun.newMvvm.base.model.BaseViewModel;
import com.zhangsun.newMvvm.common.network.listener.HttpCallbackListener;
import com.zhangsun.newMvvm.common.tools.CollectionUtil;
import com.zhangsun.newMvvm.model.bean.UserBean;
import com.zhangsun.newMvvm.model.bean.UserPageBean;
import com.zhangsun.newMvvm.model.repository.MainRepository;

public class MainViewModel extends BaseViewModel<MainRepository> {

    private MutableLiveData<ResponseData<PageBean<UserBean>>> userMutableLiveData;

    public MainViewModel(@NonNull Application application) {
        super(application, MainRepository.class);
    }

    public void getUserList(final PagingLoadTypeEnum pagingLoadTypeEnum, UserPageBean userPage) {
        baseRepository.getUserList(userPage, new HttpCallbackListener<PageBean<UserBean>>() {
            @Override
            public void onSuccess(ResponseData<PageBean<UserBean>> responseData) {
                responseData.setPagingLoadTypeEnum(pagingLoadTypeEnum);
                userMutableLiveData.setValue(responseData);
                if (responseData.getData() != null
                        && CollectionUtil.isNotEmpty(responseData.getData().getRecords())) {
                    pagingLoadType.setValue(pagingLoadTypeEnum);
                } else {
                    pagingLoadType.setValue(PagingLoadTypeEnum.MORE.equals(pagingLoadTypeEnum) ? PagingLoadTypeEnum.MORE_NO_MORE : pagingLoadTypeEnum);
                }
            }

            @Override
            public void onError(ResponseData responseData) {
                error.setValue(responseData);
                pagingLoadType.setValue(pagingLoadTypeEnum);
            }
        });
    }

    public LiveData<ResponseData<PageBean<UserBean>>> getUserData() {
        if (userMutableLiveData == null) {
            userMutableLiveData = new MutableLiveData<>();
        }
        return userMutableLiveData;
    }
}
